<template>
    <section>
        <el-dialog
                :title="template.id == 0 ? '添加任务' : '编辑任务' "
                :visible.sync="visible"
                :value="value"
                @close="close"
                width="800px"
        >
            <el-steps :active="step" finish-status="success">
                <el-step title="任务信息"/>
                <el-step title="任务指标"/>
                <el-step title="方案配置"/>
            </el-steps>
            <div v-if="step===0">
                <el-form
                        :model="template"
                        :rules="rules"
                        label-width="80px"
                        size="small"
                        ref="templateForm"
                >
                    <el-form-item label="名称" prop="name">
                        <el-input
                                v-model="template.name"
                                auto-complete="off"
                                maxlength="32"
                                :disabled="readonly"
                                suffix-icon="fa fa-vcard"
                                placeholder="请输入任务名称"
                        />
                    </el-form-item>
                    <!--<el-form-item label="分类" prop="templateSort">-->
                        <!--<el-select v-model="template.templateSort" :disabled="readonly" placeholder="请选择任务分类">-->
                            <!--<el-option-->
                                    <!--v-for="item in templateSorts"-->
                                    <!--:key="item.value"-->
                                    <!--:label="item.name"-->
                                    <!--:value="item.value"-->
                            <!--/>-->
                        <!--</el-select>-->
                    <!--</el-form-item>-->

                    <el-form-item label="任务类型" prop="taskType">
                        <el-select v-model="template.taskType" @change="taskTypeChange" :disabled="readonly"
                                   placeholder="请选择任务类型">
                            <el-option
                                    v-for="item in taskTypes"
                                    :key="item.value"
                                    :label="item.name"
                                    :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="执行时间" prop="rangTime">
                        <el-date-picker :disabled="readonly"
                                        v-model="template.rangTime"
                                        type="daterange"
                                        @change="rangChange"
                                        value-format="yyyy-MM-dd"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="描述" prop="desc">
                        <el-input :disabled="readonly"
                                  v-model="template.desc"
                                  auto-complete="off"
                                  type="textarea"
                                  maxlength="128"
                                  suffix-icon="fa fa-mobile"
                                  placeholder="请填写描述"
                        />
                    </el-form-item>
                </el-form>
                <div style="text-align: center">
                    <el-button size="small" @click="cancel('templateForm')">取 消</el-button>
                    <el-button size="small" type="primary" @click="submit('templateForm')">下一步</el-button>
                </div>
            </div>

            <div v-if="step===1">
                <el-row>
                    <el-col :span="6" :offset="17">
                        <el-button
                                type="primary"
                                icon="el-icon-fa-plus"
                                size="small" v-if="!readonly"
                                @click="editShow=true"
                        >添加指标
                        </el-button>
                    </el-col>
                </el-row>
                <el-table :data="dataList" border stripe style="width: 100%">
                    <el-table-column prop="id" label="ID"/>
                    <el-table-column prop="name" label="名称"/>
                    <el-table-column prop="score" label="积分"/>
                    <el-table-column label="操作" v-if="!readonly">
                        <template slot-scope="scope">
                            <el-button-group>
                                <el-button
                                        title="编辑"
                                        size="mini"
                                        type="primary"
                                        icon="el-icon-fa-edit"
                                        @click="quotaEdit(scope.row)"
                                >编辑
                                </el-button>
                                <el-button
                                        title="删除"
                                        size="mini"
                                        type="primary"
                                        icon="el-icon-fa-trash"
                                        @click="quotaDelete(scope.row)"
                                >删除
                                </el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
                <el-dialog
                        :title="quota.id===0?'添加指标':'编辑指标'"
                        :visible.sync="editShow"
                        append-to-body
                        width="30%"
                >
                    <el-form :model="quota" :rules="rules" ref="quotaForm">
                        <el-form-item label="指标名称" prop="name">
                            <el-input
                                    v-model="quota.name"
                                    auto-complete="off"
                                    maxlength="32"
                                    suffix-icon="fa fa-cube"
                                    placeholder="请输入任务指标名称"
                            />
                        </el-form-item>
                        <el-form-item label="分数" prop="checkNum">
                            <el-input
                                    v-model="quota.score"
                                    auto-complete="off"
                                    maxlength="32"
                                    suffix-icon="fa fa-credit-card"
                                    placeholder="请输入任务指标分数"
                            />
                        </el-form-item>
                        <el-form-item label="描述" prop="desc">
                            <el-input
                                    v-model="quota.desc"
                                    auto-complete="off"
                                    type="textarea"
                                    maxlength="128"
                                    suffix-icon="fa fa-mobile"
                                    placeholder="请填写描述"
                            />
                        </el-form-item>
                    </el-form>
                    <div style="text-align: center;margin-top: 20px">
                        <el-button size="small" @click="cancelQuota('quotaForm')">取 消</el-button>
                        <el-button size="small" type="primary" @click="quotaSubmit('quotaForm')">确 定</el-button>
                    </div>
                </el-dialog>
                <div style="text-align: center;margin-top: 20px">
                    <!--<el-button-->
                    <!--size="small"-->
                    <!--@click="cancel">取 消-->
                    <!--</el-button>-->
                    <el-button size="small" @click="lastStep">上一步</el-button>
                    <el-button size="small" type="primary" v-if="dataList.length>0||readonly" @click="nextStep">下一步
                    </el-button>
                </div>
            </div>

            <div v-if="step===2">
                <el-form :model="plan" :rules="rules" ref="templatePlanForm">
                    <el-form-item label="方案选择" prop="materielType">
                        <el-select v-model="plan.planIds" :disabled="readonly" filterable placeholder="请选择农资方案">
                            <el-option v-for="item in plans" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div style="text-align: center;margin-top: 20px">
                    <el-button size="small" @click="lastStep">上一步</el-button>
                    <el-button size="small" type="warning" @click="skip" v-if="!readonly">跳过</el-button>
                    <el-button size="small" type="primary" @click="planSubmit">完成</el-button>
                </div>
            </div>
        </el-dialog>
    </section>
</template>
<style>
</style>
<script>
    import {mapState} from "vuex";

    export default {
        name: "AddAndEdit",

        data() {
            return {
                step: 0,
                readonly: false,
                visible: false,
                editShow: false,
                editMaterielShow: false,
                choosePlanShow: false,
                labelWidth: "",
                templateSorts: [],
                plans: [],
                taskTypes: [],
                templatePlans: [],
                dataList: [],
                materiels: [],
                templateId: 0,
                template: {
                    id: 0,
                    name: "",
                    templateSort: "",
                    taskType: "",
                    startTime: "",
                    endTime: "",
                    rangTime: [],
                    desc: ""
                },
                quota: {
                    id: 0,
                    name: "",
                    score: "",
                    templateId: 0,
                    desc: ""
                },
                plan: {
                    id: 0,
                    templateId: 0,
                    planIds: ""
                },
                rules: {
                    checkNum: [
                        {required: true, validator: this.$validator.decimalValid, trigger: "blur"}
                    ],
                    name: [{required: true, message: "请输入任务名称", trigger: "blur"}],
                    taskType: [
                        {
                            required: true,
                            message: "请选择任务类型",
                            trigger: "blur"
                        }
                    ],
                    startTime: [
                        {required: true, message: "请选择开始时间", trigger: "blur"}
                    ],
                    rangTime: [
                        {required: true, message: "请选择执行时间", trigger: "blur"}
                    ],
                    endTime: [
                        {required: true, message: "请选择结束时间", trigger: "blur"}
                    ]
                }
            };
        },
        computed: {
            ...mapState({
                codebooks: state => state.codebooks.codebooks
            })
        },
        watch: {
            value: {
                deep: true,
                immediate: true,
                handler: function (val) {
                    this.visible = val.show;
                    this.labelWidth = val.formLabelWidth || "120px";
                    this.template.id = val.template.id;
                    if (this.visible) {
                        this.loadData();
                    }
                }
            },
            visible(val) {
                if (!val) this.$emit("on-show-change", this.$data);
            }
        },
        mounted() {
            this.templateSorts = this.codebooks ? this.codebooks.templateSorts : [];
            this.taskTypes = this.codebooks ? this.codebooks.taskTypes : [];
        },
        methods: {
            rangChange(val) {
                console.log(val);
            },
            cancel(formName) {
                this.visible = false;
                this.template = {
                    id: 0
                };
                this.plan = {
                    id: 0
                };
                this.step = 0;
                if(!this.readonly){
                    this.cancelQuota('quotaForm');
                    if(this.$refs[formName]){
                        this.$refs[formName].clearValidate();
                    }
                }
                this.readonly = false;
            },
            close() {
                this.cancel('templateForm');
            },
            cancelQuota(formName) {
                if(this.$refs[formName]){
                    this.$refs[formName].clearValidate();
                }
                this.editShow = false;
                this.quota = {
                    id: 0
                };
            },
            cancelPlan() {
                this.choosePlanShow = false;
                this.plan = {
                    id: 0
                };
            },
            taskTypeChange(val) {
                this.$delete(this.template, "taskType");
                this.template.taskType = val;
            },
            handlePlan() {
                this.choosePlanShow = true;
                //查询所有的农资方案
                this.$api.plan.all(result => {
                    this.plans = result.plans;
                });
                //查询已选择的农资方案
                this.$api.template.getTemplatePlan(this.template.id, result => {
                    let plan = result.templatePlan;
                    if (plan) {
                        this.plan.planIds = plan.planId;
                    }
                });
            },
            loadData() {
                if (!this.template || !this.template.id || this.template.id <= 0) {
                    return;
                }
                this.$api.template.detail(this.template.id, result => {
                    this.template = Object.assign(result.template, {
                        templateSort: result.template.templateSort
                            ? result.template.templateSort.value
                            : "",
                        taskType: result.template.taskType
                            ? result.template.taskType.value
                            : "",
                        rangTime: [result.template.startTime, result.template.endTime]
                    });
                    this.readonly = result.template.templateStatus ? (result.template.templateStatus.value == 'UNPUBLISHED' ? false : true) : false;
                    this.$delete(this.template, 'status');
                    this.$delete(this.template, 'templateStatus');
                });
            },

            loadQuotaData(templateId) {
                this.$api.template.getQuota(templateId, quotaResult => {
                    this.dataList = quotaResult.quotas;
                });
            },
            checkDate(startTime, endTime) {
                startTime = startTime.replace("-", "/");
                endTime = endTime.replace("-", "/");
                let startDate = new Date(Date.parse(startTime));
                let endDate = new Date(Date.parse(endTime));
                let nowDate = new Date(
                    Date.parse(
                        new Date().getFullYear() +
                        "-" +
                        new Date().getMonth() +
                        "-" +
                        new Date().getDay()
                    )
                );
                if (startDate > endDate) {
                    this.$message.error("开始时间不能大于结束时间");
                    return false;
                }
                if (startDate < nowDate) {
                    this.$message.error("开始时间不能小于当前时间");
                    return false;
                }
                return true;
            },
            submit(formName) {
                if (this.readonly) {
                    this.step++;
                    return;
                }
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.template.startTime = this.template.rangTime[0];
                        this.template.endTime = this.template.rangTime[1];
                        this.template.templateSort = 'TEMPORARY';
                        if (!this.checkDate(this.template.startTime, this.template.endTime)) {
                            return;
                        }
                        const callback = result => {
                            //this.cancel();
                            this.step++;
                            //查询指标列表
                            this.templateId = result.template.id;
                            this.template.id = result.template.id;
                            this.loadQuotaData(this.templateId);
                        };
                        this.template.id
                            ? this.$api.template.update(this.template, callback)
                            : this.$api.template.save(this.template, callback);
                    } else {
                        return false;
                    }
                });
            },
            quotaSubmit(formName) {
                if (this.readonly) {
                    this.step++;
                    return;
                }
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.loadQuotaData(this.templateId);
                            this.cancelQuota(formName);
                        };
                        this.quota.templateId = this.templateId;
                        this.quota.id
                            ? this.$api.template.editQuota(this.quota, callback)
                            : this.$api.template.addQuota(this.quota, callback);
                    } else {
                        return false;
                    }
                });
            },
            planSubmit() {
                if (this.readonly) {
                    this.cancel();
                    return;
                }
                if (this.template.taskType != "FARMING") {
                    this.$message.error("该任务模板不需要选择农资方案");
                    return;
                }
                const callback = () => {
                    // this.loadTemplatePlanData(this.templateId);
                    // this.cancelPlan();
                    this.cancel('templateForm');
                };
                if (!this.plan.planIds) {
                    this.$message.error("如不需要选择农资方案，请点击跳过");
                    return;
                }
                this.plan.templateId = this.templateId;
                this.plan.planIds = [this.plan.planIds];
                this.plan.id > 0
                    ? this.$api.template.editTemplatePlan(this.plan, callback)
                    : this.$api.template.addTemplatePlan(this.plan, callback);
            },
            loadTemplatePlanData() {
                this.$api.template.getTemplatePlan(this.templateId, result => {
                    this.plan = result.templatePlan;
                });
            },
            lastStep() {
                if (this.step > 0) {
                    this.step--;
                }
            },
            nextStep() {
                this.step++;
                if (this.step === 2) {
                    this.handlePlan();
                }
            },
            skip() {
                this.cancel('templateForm');
            },
            quotaEdit(row) {
                this.$api.template.quotaDetail(row.id, result => {
                    this.quota = result.quota;
                    this.$delete(this.quota, "status");
                    this.editShow = true;
                });
            },
            quotaDelete(row) {
                this.$confirm("此操作将删除该指标, 是否继续?", "删除提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.$api.template.delQuota(row.id, () => {
                        this.$message({
                            type: "success",
                            message: "删除指标成功",
                            onClose: () => {
                                this.loadQuotaData(row.templateId);
                            }
                        });
                    });
                });
            }
        },
        props: {
            value: {
                type: Object,
                default: function () {
                    return {
                        show: false,
                        formLabelWidth: "100px",
                        template: {
                            id: 0
                        }
                    };
                }
            }
        }
    };
</script>
